

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/base/BaseProvide.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/bean/shopcart/ShopingCartBean.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/bean/subitorder/SubitOrderEntity.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/Constant.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/ImageHelper.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/RouteHelper.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/ViewHelper.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/view/cartshoppingwidget/CartShopVM.dart';


ValueNotifier<List<ShoppingCartLists>> selectCartGoodVN=ValueNotifier([]);

class CartListWidget extends StatelessWidget {

  final CartShopVM cartShopVM=CartShopVM();

  // 计算总价
  double calculateAllMoney(List<ShoppingCartLists> list){
    double money=0;
    for(int i=0;i<list.length;i++){
      if(!list[i].isCheck){
        break;
      }
      if(list[i].isAskPriceFlag==1 ){
        return -1;
      }
      money+=(list[i].price??0)*(list[i].quantity??0);
    }
    return money;
  }
  //
  void toJieSuan(BuildContext context){
    List<SubitOrderEntity> list=[];
    selectCartGoodVN.value.forEach((element) {
      if(element.isCheck){
        list.add(SubitOrderEntity(cartId:"${element.productSkuId}" ,num: "${element.quantity}",productType:"${element.productType}" ,skuCode: "${element.productSkuCode}"));
      }
    });
    if(list.isEmpty){
      showCenterToast("大哥，你还没有选商品呢");
      return;
    }
    toSubitOrder(context, list);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
            color: Color(ConstantColors.mainBackgroundColor),
            child: Column(
               children: [
                 //标题栏
                 DufTitleBar(backColor: Colors.black,titleText: "购物车",more: InkWell(onTap: (){ showCenterToast("你没有权限管理"); },child: Text("管理",style: TextStyle(fontSize: 16.sp,color: Color(0xff2D3137),decoration: TextDecoration.none),)),color: Colors.white,),
                 Expanded(
                    child: StoreListWidget(cartShopVM),
                  ),
                 //底部栏
                 ValueListenableBuilder(
                   builder: (BuildContext context,List<ShoppingCartLists> value, Widget? child) {
                     var allMoney = calculateAllMoney(value);
                     int cartAllNum=0;
                     cartShopVM.shoppingCartList.forEach((element) {
                       cartAllNum+=element.shoppingCartLists?.length??0;
                     });
                     return Container(
                       height: 50.h,
                       color: Colors.white,
                       alignment: Alignment.centerLeft,
                       padding: EdgeInsets.fromLTRB(26.sp, 0, 26.sp, 0),
                       child: Row(
                         children: [
                               DufCheckbox(value: cartAllNum==selectCartGoodVN.value.length&&cartAllNum!=0, radius: 9.sp,onChanged: (value){
                             cartShopVM.shoppingCartList.forEach((element) {
                                _editorStoreSelectState(element, value);
                             });
                             cartShopVM.shoppingCartList=notifyList(cartShopVM,cartShopVM.shoppingCartList);
                             selectCartGoodVN.notifyListeners();
                           },),
                           Padding(padding: EdgeInsets.all(4.sp)),
                           Text("全选",style: TextStyle(fontSize: 12.sp,color: Color(0xff2D3137)),),
                           Padding(padding: EdgeInsets.all(4.sp)),
                           Text("合计:",style: TextStyle(fontSize: 16.sp,color: Color(0xff2D3137)),),
                           Padding(padding: EdgeInsets.all(4.sp)),
                           Expanded(child: PriceInfoDealWith(priceText: '$allMoney',symbolSize: 16.sp,priceSize: 16.sp,isAskPriceFlag: allMoney==-1?1:0,)),
                           //结算按钮
                           TextButton(onPressed: (){
                             toJieSuan(context);
                           }, child: Text("去结算(${value.length})",style: TextStyle(color: Colors.white,fontSize: 14.sp),),
                             style:ButtonStyle(
                               minimumSize: MaterialStateProperty.all(Size(108.sp, 38.sp)),
                               maximumSize: MaterialStateProperty.all(Size(128.sp, 38.sp)),
                               backgroundColor:MaterialStateProperty.all(Color(ConstantColors.mainColor)),
                               shape:MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(19.sp))),
                             ),
                           )
                         ],
                       ),
                     );
                   },
                   valueListenable: selectCartGoodVN,
                 )
               ],
            ),
      ),
    );
  }
}

class StoreListWidget extends StatefulWidget {

  CartShopVM cartShopVM;

  ScrollController _controller=ScrollController();

  StoreListWidget(this.cartShopVM);

  @override
  _StoreItemWidgetState createState() => _StoreItemWidgetState();
}

class _StoreItemWidgetState extends State<StoreListWidget> {

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
       widget.cartShopVM.getShoppingCart();
    });
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (BuildContext context) {
         return widget.cartShopVM;
      },
      child: Selector(
        selector: (BuildContext , CartShopVM vm) {
          return vm.shoppingCartList;
        },
        builder: (BuildContext context,List<CartShoppingBean>? value, Widget? child) {
            return ListView.builder(
              controller: widget._controller,
              padding: EdgeInsets.zero,
              itemCount: value?.length??0,
              itemBuilder: (BuildContext context, int index) {
                CartShoppingBean? bean= value?[index];
                return StoreItemWidget(widget._controller,bean,widget.cartShopVM);
              },);
        },
      ),
    );
  }
}

//店铺 级  item
class StoreItemWidget extends StatelessWidget {

  ScrollController controller;
  CartShoppingBean? bean;
  CartShopVM cartShopVM;
  StoreItemWidget(this.controller, this.bean, this.cartShopVM);

  @override
  Widget build(BuildContext context) {

    return Container(
      margin: EdgeInsets.fromLTRB(12.sp, 12.sp, 12.sp, 0),
      padding: EdgeInsets.all(14.sp),
      decoration: ShapeDecoration(color:Colors.white,shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10.r)))),
      child: Column(
        children: [
          //店铺名称
          Row(
            children: [
              DufCheckbox(value: _checkStoreSelectState(bean), radius: 9.sp,onChanged: (value){
                  _editorStoreSelectState(bean,value);
                  cartShopVM.shoppingCartList= notifyList(cartShopVM,cartShopVM.shoppingCartList);
                  selectCartGoodVN.notifyListeners();
              },),
              Padding(padding: EdgeInsets.fromLTRB(8.sp, 0, 0, 0)),
              Image.asset(assetPath("ic_tab_store_def.png"),height: 15.sp,fit: BoxFit.fitHeight,),
              Padding(padding: EdgeInsets.fromLTRB(4.sp, 0, 0, 0)),
              Text(bean?.storeName??"",style: TextStyle(fontSize: 16.sp,color: Color(0xff2D3137),overflow: TextOverflow.ellipsis),maxLines: 1,softWrap: true,),
              Padding(padding: EdgeInsets.fromLTRB(4.sp, 0, 0, 0)),
              Image.asset(assetPath("ic_my_right_arrow.png"),height: 9.sp,fit: BoxFit.fitHeight,),
            ],
          ),
          ListView.separated(
            padding: EdgeInsets.fromLTRB(0, 20.sp, 0 , 0),
            controller:controller,
            itemCount: bean?.shoppingCartLists?.length??0,shrinkWrap: true,
            itemBuilder: (BuildContext context, int index) {
              ShoppingCartLists? shoppingCartList = bean?.shoppingCartLists?[index];
              return GoodsItemWidget(shoppingCartList,cartShopVM);
            }, separatorBuilder: (BuildContext context, int index) {  return Divider(height: 20.h,color: Color(ConstantColors.mainBackgroundColor),); },),
         ],
      ),
    );
  }
}

class GoodsItemWidget extends StatelessWidget {

  CartShopVM cartShopVM;
  ShoppingCartLists? shoppingCartList;

  GoodsItemWidget(this.shoppingCartList,this.cartShopVM);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Row(
           children: [
             DufCheckbox(value: shoppingCartList?.isCheck==true?true:false, radius: 9.sp,onChanged: (value){
               _editorGoodsSelectState(shoppingCartList, value);
               cartShopVM.shoppingCartList=notifyList(cartShopVM,cartShopVM.shoppingCartList);
               selectCartGoodVN.notifyListeners();
             },),
             Padding(padding: EdgeInsets.fromLTRB(0, 0, 10.sp, 0)),
             DufRoundedWidget(assetImage(shoppingCartList?.productPic??"",width: 90.sp,height: 90.sp,fit: BoxFit.fill)),
             Expanded(
               child: Container(
                 height: 90.sp,
                 alignment: Alignment.centerLeft,
                 margin: EdgeInsets.fromLTRB(12.sp, 0, 0, 0),
                 child: Column(
                   crossAxisAlignment: CrossAxisAlignment.start,
                   mainAxisAlignment: MainAxisAlignment.spaceBetween,
                   children: [
                     Text("${shoppingCartList?.productName??"--"}",style: TextStyle(fontSize: 14.sp,color: Color(0xff2D3137),overflow: TextOverflow.ellipsis),maxLines: 1,softWrap: true,),
                     Container(
                         padding: EdgeInsets.fromLTRB(8.sp,5.sp, 8.sp, 5.sp),
                         decoration: ShapeDecoration(color: Color(0xffF5F6F8), shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(11.r)))),
                         child: Text("${shoppingCartList?.productAttr??""}",strutStyle: StrutStyle(height: 1),style: TextStyle(fontSize: 12.sp,color: Color(0xff999999),overflow: TextOverflow.ellipsis),maxLines: 1,softWrap: true,)),
                     Row(
                       mainAxisSize: MainAxisSize.max,
                       mainAxisAlignment: MainAxisAlignment.end,
                       children: [
                         Expanded(child: PriceInfoDealWith(priceText: '${shoppingCartList?.price??""}',priceSize: 20.sp,isAskPriceFlag:shoppingCartList?.isAskPriceFlag,)),
                         InkWell(onTap: (){
                           showBottomToast("偷偷告诉你 ！ 这个我没有写逻辑");
                         },child: Container(padding:EdgeInsets.all(9.sp),child: Image.asset(assetPath("ic_cart_minus.png"),color: Color(0xff2D3137),width: 12.sp,fit: BoxFit.fitWidth))),
                         Container(
                           alignment: Alignment.center,
                           constraints:BoxConstraints(minWidth: 35.sp,maxWidth: 50.sp) , padding: EdgeInsets.all(3.sp),
                           decoration: ShapeDecoration(color: Color(0xffF5F6F8), shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.r)))),
                           child: Text('${shoppingCartList?.quantity??""}',style: TextStyle(fontSize: 12.sp,color: Color(0xff2D3137),overflow: TextOverflow.ellipsis),maxLines: 1,softWrap: true,)),
                         InkWell(onTap: (){
                           showBottomToast("偷偷告诉你 ！ 这个我没有写逻辑");
                         },child: Container(padding:EdgeInsets.all(9.sp),child: Image.asset(assetPath("ic_cart_add.png"),width: 12.sp,fit: BoxFit.fitWidth))),
                       ],
                     )
                   ],
                 ),
               ),
             )
           ],
        ),
    );
  }
}

//修改 购物车的店铺下的商品是否是都是选中状态
bool _checkStoreSelectState(CartShoppingBean? bean){
  if(bean==null){
    return false;
  }
  bool isSelectAll=true;
  for(int i=0;i<(bean.shoppingCartLists?.length??0);i++){
    if(bean.shoppingCartLists?[i].isCheck!=true){
      isSelectAll=false;
      continue;
    }
  }
  bean.isCheck=isSelectAll;
  return isSelectAll;
}

//修改 购物车的店铺下的商品选中状态
void _editorStoreSelectState(CartShoppingBean? bean,bool value){
  if(bean==null){
    return;
  }
  bean.isCheck=value==true?true:false;
  bean.shoppingCartLists?.forEach((element) {
    _editorGoodsSelectState(element, value);
  });
}

//修改 购物车的店铺下的商品选中状态
void _editorGoodsSelectState(ShoppingCartLists? bean,bool value){
  if(bean==null){
    return;
  }
  bean.isCheck=value==true?true:false;
  if(value==true){
    if(!selectCartGoodVN.value.contains(bean)){
      selectCartGoodVN.value.add(bean);
    }
  }else{
    selectCartGoodVN.value.remove(bean);
  }
}